<!-- ^2_3^ -->
<template>
  <a-modal
    :title="title"
    :width="640"
    :visible="visible"
    :confirmLoading="loading"
    @ok="() => { $emit('ok') }"
    @cancel="() => { $emit('cancel') }"
  >
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout">
        <a-form-item v-show="model && model.id > 0" label="角色ID">
          <a-input v-decorator="['id', { initialValue: 0 }]" disabled />
        </a-form-item>
        <a-form-item label="角色名称">
          <a-input v-decorator="['r_name', {rules: [{required: true, min: 1, message: '请输入至少1个字符'}]}]" />
        </a-form-item>
        <a-form-item label="权限节点">
          <a-tree-select
            ref="treeSelect"
            style="width: 100%"
            :tree-data="treeData"
            tree-checkable
            treeCheckStrictly
            :show-checked-strategy="SHOW_ALL"
            search-placeholder="Please select"
            v-decorator="['nodes', {}]"
          />
        </a-form-item>
        <a-form-item label="备注描述">
          <a-input v-decorator="['remark', {}]" />
        </a-form-item>
        <a-form-item label="状态">
          <a-radio-group v-decorator="['status', { initialValue: 1 }]">
            <a-radio :value="0">禁用</a-radio>
            <a-radio :value="1">正常</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
// ^2_3^
import pick from 'lodash.pick'
import { menuTree } from '@/api/menu'
import { TreeSelect } from 'ant-design-vue'
const SHOW_ALL = TreeSelect.SHOW_ALL

// 表单字段
const fields = ['id', 'r_name', 'remark', 'status', 'nodes']

export default {
  name: 'RoleModal',
  components: {
    TreeSelect
  },
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    }
  },
  data () {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      }
    }
    return {
      form: this.$form.createForm(this),
      SHOW_ALL,
      treeData: []
    }
  },
  created () {
    this.getTreeValue()

    // 防止表单未注册
    fields.forEach(v => this.form.getFieldDecorator(v))

    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      this.model && this.form.setFieldsValue(pick(this.model, fields))
    })
  },
  computed: {
    title () {
      return this.model === null ? '角色新增' : '角色编辑'
    }
  },
  methods: {
    // 菜单节点树形数据
    getTreeValue () {
      menuTree().then(res => {
        if (res.code === 0) {
          this.treeData = res.data
        }
      })
    }
  }
}
</script>
